﻿using K9Nano.Caching;
using K9Nano.Dependency;
using K9Nano.Exceptions;
using K9Nano.Pushing;
using Microsoft.Extensions.Logging;

namespace K9Nano.Captcha.Sms;

internal class SmsCaptchaManager(ICaptchaManager captchaManager,
    ISmsSender sender,
    ITypedCache<SmsAntiCache> antiCache) : ISmsCaptchaManager, ISingletonDependency
{
    public async ValueTask<bool> SendAsync(string phone, string templateId, TimeSpan expire, int length = 4, CancellationToken cancellation = default)
    {
        if (antiCache.Exists(phone))
        {
            throw FriendlyException.BadRequest("验证码发送过于频繁，请稍后再试");
        }
        var code = captchaManager.GenerateCode(phone, expire, length);
        var result = await sender.SendTemplateAsync(phone, templateId, [code], cancellation);
        if (result)
        {
            antiCache.Add(phone, new SmsAntiCache(phone), absoluteTimeout: TimeSpan.FromSeconds(60));
        }
        return result;
    }

    public bool Validate(string phone, string code)
    {
        return captchaManager.Validate(phone, code);
    }
}

/// <summary>
/// 短信验证码防刷包
/// </summary>
/// <param name="phone"></param>
internal record SmsAntiCache(string phone);